package com.chat;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.borland.jbcl.layout.*;
import java.net.*;//需要增加的包
import java.io.*;
import java.util.Vector;
import java.util.StringTokenizer;
import java.lang.Thread;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */

public class Frame2 extends JFrame {
  JPanel contentPane;
  JPanel jPanel1 = new JPanel();
  JPanel jPanel2 = new JPanel();
  XYLayout xYLayout1 = new XYLayout();
  BorderLayout borderLayout1 = new BorderLayout();
  BorderLayout borderLayout2 = new BorderLayout();
  JPanel jPanel3 = new JPanel();
  JLabel jLabel1 = new JLabel();
  JLabel jLabel2 = new JLabel();
  JLabel jLabel3 = new JLabel();
  PaneLayout paneLayout1 = new PaneLayout();
  JPanel jPanel4 = new JPanel();
  JLabel jLabel4 = new JLabel();
  JLabel jLabel5 = new JLabel();
  JLabel jLabel6 = new JLabel();
  PaneLayout paneLayout2 = new PaneLayout();
  JScrollPane jScrollPane1 = new JScrollPane();
  JScrollPane jScrollPane2 = new JScrollPane();
  JTextArea jTextArea2 = new JTextArea();
  JPanel jPanel5 = new JPanel();
  JTextField jTextField1 = new JTextField();
  PaneLayout paneLayout3 = new PaneLayout();
  JButton send = new JButton();
  JButton sysexit = new JButton();
  JTextField jTextField2 = new JTextField();
  java.awt.List list1 = new java.awt.List();
  JButton link = new JButton();//用来列出目前连接的客户数

//定义相关变量
 static ServerSocket serverSocket=null;//建立服务器的socket
  Socket socket=null;  //用来存储一个连接套接字
  BufferedReader cin=null;//用来实现接受从客户端发来的数据流
  PrintWriter cout=null;//用来实现向客户端发送信息的流
  static Vector<Client> clients=new Vector<Client>(20);   //用vector向量数组存储连接客户变量
  static int active_connects=0;//记录目前连接的客户数



  //Construct the frame
  public Frame2() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
      jbInit();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
  //Component initialization
  private void jbInit() throws Exception  {
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(xYLayout1);
    this.setLocale(java.util.Locale.getDefault());
    this.setSize(new Dimension(407, 379));
    this.setTitle("网络聊天服务器");
    jPanel1.setLayout(borderLayout1);
    jPanel2.setLayout(borderLayout2);
    jLabel1.setBorder(BorderFactory.createEtchedBorder());
    jLabel1.setText("用户名");
    jLabel2.setBorder(BorderFactory.createEtchedBorder());
    jLabel2.setText("IP地址");
    jLabel3.setBorder(BorderFactory.createEtchedBorder());
    jLabel3.setToolTipText("");
    jLabel3.setText("连接情况");
    jPanel3.setLayout(paneLayout1);
    jLabel4.setBorder(BorderFactory.createEtchedBorder());
    jLabel4.setText("信息类型");
    jLabel5.setBorder(BorderFactory.createEtchedBorder());
    jLabel5.setText("信息来源");
    jLabel6.setBorder(BorderFactory.createEtchedBorder());
    jLabel6.setText("信息内容");
    jPanel4.setLayout(paneLayout2);
    jTextField1.setEditable(false);
    jTextField1.setText("");
    jPanel5.setLayout(paneLayout3);
    send.setText("发送");
    send.addActionListener(new Frame2_send_actionAdapter(this));
    sysexit.setText("退出");
    sysexit.addActionListener(new Frame2_sysexit_actionAdapter(this));
    jTextArea2.setText("");
    link.setText("连接");
    link.addActionListener(new Frame2_link_actionAdapter(this));
    contentPane.add(jPanel1,    new XYConstraints(-2, 0, 402, 152));
    jPanel1.add(jPanel3, BorderLayout.NORTH);
    jPanel1.add(jScrollPane1, BorderLayout.CENTER);
    jScrollPane1.getViewport().add(list1, null);
    contentPane.add(jPanel2,     new XYConstraints(-1, 160, 401, 140));
    jPanel2.add(jPanel4,  BorderLayout.NORTH);
    jPanel4.add(jLabel4,           new PaneConstraints("jLabel4", "jLabel4", PaneConstraints.ROOT, 0.5f));
    jPanel4.add(jLabel5,           new PaneConstraints("jLabel5", "jLabel4", PaneConstraints.RIGHT, 0.7431421f));
    jPanel4.add(jLabel6,           new PaneConstraints("jLabel6", "jLabel5", PaneConstraints.RIGHT, 0.36577183f));
    jPanel2.add(jScrollPane2, BorderLayout.CENTER);
    jPanel2.add(jPanel5, BorderLayout.SOUTH);
    contentPane.add(jTextField2, new XYConstraints(1, 295, 306, 31));
    contentPane.add(jTextField1,  new XYConstraints(2, 329, 242, -1));
    contentPane.add(send,  new XYConstraints(328, 301, 60, 22));
    contentPane.add(sysexit,   new XYConstraints(329, 329, 60, 22));
    contentPane.add(link, new XYConstraints(261, 330, 56, 22));
    jScrollPane2.getViewport().add(jTextArea2, null);
    jPanel3.add(jLabel1,        new PaneConstraints("jLabel1", "jLabel1", PaneConstraints.ROOT, 0.5f));
    jPanel3.add(jLabel2,        new PaneConstraints("jLabel2", "jLabel1", PaneConstraints.RIGHT, 0.8557214f));
    jPanel3.add(jLabel3,        new PaneConstraints("jLabel3", "jLabel2", PaneConstraints.RIGHT, 0.5826087f));
  }
  //File | Exit action performed
  public void jMenuItemClear_actionPerformed(ActionEvent e) {
    System.exit(0);
  }
  //Help | About action performed
  //Overridden so we can exit when window is closed
  protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
      jMenuItemClear_actionPerformed(null);
    sendClients(new StringBuffer("QUIT:"+"SERVER"));
   closeAll();
   System.exit(0);

    }
  }

//添加的方法！！！！
  public static void notifyRoom(){//监视聊天窗口的连接变化,不
    //断刷新clients数组并刷新用户列表信息
   StringBuffer people=new StringBuffer("PEOPLE");
   //增加PEOPLE表示是客户列表信息
   for(int i=0;i<clients.size();i++)
   {
     Client c=(Client)clients.elementAt(i);
     people.append(":"+c.name);
   }
   sendClients(people);
  }

public static boolean  checkName(Client newClient)
  {
    for(int i=0;i<clients.size();i++)
    {
      Client c=(Client)clients.elementAt(i);
      if((c!=newClient)&&c.equals(newClient.name))
        return false;
    }
    return true;
  }

  public synchronized void disconnect(Client c)//缺少static
  {
    try{
     jTextArea2.append("系统消息：             "
                       +c.name+"        断开连接\n");
     active_connects--;  //连接数减1
     c.send(new StringBuffer("QUIT"+":"+c.name));
                      //向客户发送断开信息
     clients.removeElement(c);
     jTextField1.setText("目前已经有"+clients.size()+"用户连接");
     c.socket.close();//断开连接
   }
   catch(IOException e)
   {
     jTextArea2.append("系统消息："+"Error "+e);
   }
  }

  public  static synchronized void sendClients(StringBuffer msg)
  {//发送信息到所有用户
   for(int i=0;i<clients.size();i++){
   Client c=(Client)clients.elementAt(i);
   c.send(msg);
   }
  }

  public synchronized void sendtoClient(StringBuffer msg,String name)
       //将信息发送到特定的单个用户
     {
       for(int i=0;i<clients.size();i++)
    {
      Client c=(Client)clients.elementAt(i);
      if(c.name.equalsIgnoreCase(name))
      {
       c.send(msg);
       break;
      }
      }
     }


  public void closeAll()//关闭所有游的连接信息
  {
    while(clients.size()>0)
    //需要在整个数组中将每一个连接遍历，然后删除信息
    {
      Client c=(Client)clients.firstElement();
      try{
        c.socket.close();
      }
      catch(IOException e){
        jTextArea2.append("系统消息："+"        聊天服务器"+ "   Error  "+e);
      }
      finally{
        clients.removeElement(c);
        //从clients数组中删除客户相关的socket信息
      }
    }
  }
class Client extends Thread{
      String name;      //用来存储客户的连接姓名
      String ip;         //用来存储客户的连接IP
      DataInputStream dis;  //用于实现接受从客户端发送来的数据流
      PrintStream ps;  //用来实现向客户端发送信息的打印流
      Socket socket;

      public  Client(Socket s)       //Client 线程的构造器
     {
       socket=s;
        try{
             dis=new DataInputStream(s.getInputStream());
             //存储特定客户socket的输入流，
              //接受s客户发送到服务器端的信息
             ps=new PrintStream(s.getOutputStream());
              //存储特定客户socket的输出流，
              //发送服务器给s客户的信息

              String info=dis.readLine();
              //String info = dis.readUTF();
              //读取接受到的信息
              StringTokenizer stinfo=new StringTokenizer(info,":");
              //读取用"："分开的分段字符
              String head=stinfo.nextToken();
               //用head存储关键字的头信息
               if(stinfo.hasMoreTokens())
                name=stinfo.nextToken();
               //关键字的第二个数据段是客户的名称
               if(stinfo.hasMoreTokens())
               ip=stinfo.nextToken();
                //关键字的第三个数据段是客户的IP地址
                jTextArea2.append("系统消息：        "+name+"/"+ip+"  已经连接\n");
                 }
      catch(IOException e){
        jTextArea2.append("系统消息：       聊天服务器"+"Error  "+e);
      }
  }

      public void send(StringBuffer msg)
        //实现向客户端发送信息的方法
        {
        ps.println(msg);
        //用打印流发送信息
        ps.flush();
      }


    public void run(){            //线程的运行方法
        while(true){
          String line=null;
          try{
            line=dis.readLine();       //读取客户端发送的数据流

          }
          catch(IOException e)
          {
            jTextArea2.append("系统消息："+"     聊天服务器"+"  Error：  "+e);
            disconnect(this);
            notifyRoom();
            return ;
          }
          if(line==null)        //客户已经离开
          {
            disconnect(this);
            notifyRoom();
            return;
          }
          StringTokenizer st=new StringTokenizer(line,":");
          String keyword=st.nextToken();//存储关键字，判断消息类型
          String broadcast=st.nextToken();//存储消息是属于广播，还是属于单播
                                          //如果单播，则记录的是目标用户名
          if(keyword.equalsIgnoreCase("MSG"))  //如果关键字是MSG，则是客户端发送的聊天信息
          {
            StringBuffer message=new StringBuffer("MSG:");//在服务器端建立一个缓冲区，用于信息的发送
            message.append(broadcast+":");
            message.append(st.nextToken("\0"));
            if(broadcast.equalsIgnoreCase("BROAD"))
            {
              sendClients(message);
            }
            else
            {
              sendtoClient(message,broadcast);
            }
          }
          else if(keyword.equalsIgnoreCase("QUIT"))   //如果关键字是QUIT，则是客户端发送的退出信息
          {
            list1.clear();
            disconnect(this);
            for(int i=0;i<clients.size();i++)
            {
            Client listdata1=(Client)clients.elementAt(i);
            list1.add(listdata1.name+"               "+listdata1.ip+"     已经连接",i);
            }
            notifyRoom();
            this.stop();
          }
        }
    }
    }

  void send_actionPerformed(ActionEvent e) {
  StringBuffer info=new StringBuffer("MSG");
  info.append(":"+"BROAD:"+"SERVER"+":");
  info.append(jTextField2.getText());
  sendClients(info);
  jTextField2.setText("");
  }


  void sysexit_actionPerformed(ActionEvent e) {
   sendClients(new StringBuffer("QUIT:"+"SERVER"));
   closeAll();
   System.exit(0);
  }

  void link_actionPerformed(ActionEvent e) {
    //进行服务器的初始化建立
     if (serverSocket == null) {
        try {
          serverSocket = new ServerSocket(6000);
          jTextArea2.append("系统提示：       聊天服务器"+

                            "                系统开始启动......\n");
        }
        catch (IOException ee) {
        	ee.printStackTrace();
          jTextArea2.append("系统消息：       聊天服务器                "
                            + e.toString() + "\n");
        }
      }
      if(serverSocket!=null){
           jTextArea2.append("系统消息：       聊天服务器"+
                             "                已经启动\n");
          Thread a=new watch();
                    //启动监视线程
          a.start();
      }
  }
class watch extends Thread{
     int i=0;
 public void run(){

  while(true){
    if(clients.size()<20)
          //当客户数目小于20的时候开始连接
        {
          try{
            socket=serverSocket.accept();
          }
          catch(IOException ee){
          jTextArea2.append("系统消息：     聊天服务器        "+
                            ee.toString()+" 用户连接失败\n");
          }


     do{
       Client c=new Client(socket);
       //定义并实例化一个Client线程，每一个线程对应一个客户连接
       clients.addElement(c);
       //加入到clients数组中
       if(checkName(c))
       {
       int num=active_connects+1;
       active_connects++;//连接数目加1
       jTextField1.setText("目前已经有"+num+"用户连接");
      //在状态栏中显示目前的活动数目
       Client listdata=(Client)clients.elementAt(i);
       list1.add(listdata.name+"               "+listdata.ip+"     已经连接",i);
       c.start();
      //启动线程
       notifyRoom();
    //监视聊天窗口的连接变化
       }
       else{
         c.ps.println("FaultName");
        //检查名字不合法，则在发送流中发送FaultName
         disconnect(c);
         //断开连接
       }
      i++;
       break;
     }
     while(i<clients.size());
      }
      else{  //如果超过连接数目
        try{
          Thread.sleep(400);  //睡眠一段时间然后重新连接
        }
        catch(InterruptedException ee)
        {
        }
      }
      }  //end of while*/
     }//end of run
  }////end of watch class

}
class Frame2_send_actionAdapter implements java.awt.event.ActionListener {
  Frame2 adaptee;

  Frame2_send_actionAdapter(Frame2 adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.send_actionPerformed(e);
  }
}

class Frame2_sysexit_actionAdapter implements java.awt.event.ActionListener {
  Frame2 adaptee;

  Frame2_sysexit_actionAdapter(Frame2 adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.sysexit_actionPerformed(e);
  }
}

class Frame2_link_actionAdapter implements java.awt.event.ActionListener {
  Frame2 adaptee;

  Frame2_link_actionAdapter(Frame2 adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.link_actionPerformed(e);
  }

}
